package root.electronclass.electronclass.grade.homework.viewmodel

import androidx.lifecycle.*
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.ext.MMdd
import root.electronclass.electronclass.ext.chineseNumber
import root.electronclass.electronclass.ext.toDateMMdd
import root.electronclass.electronclass.ext.toDateYyyyMMdd
import root.electronclass.electronclass.ext.yyyyMMdd
import root.electronclass.electronclass.grade.model.*
import root.electronclass.electronclass.grade.repository.ClassRepository
import root.electronclass.electronclass.grade.viewmodel.WeekType
import java.util.*

/**
 *
 * @author Lokiy
 * @date 2023/2/4 14:07
 */
class ClassHomeworkViewModel : ViewModel() {

    /**
     * -1 上一周 0本周 1下一周
     */
    private val type = MutableLiveData(0)
    val selectDate = MutableLiveData(Calendar.getInstance().timeInMillis.toDateYyyyMMdd())

    val data: LiveData<List<ClassHomeworkItem>> = selectDate.switchMap {
        liveData(CoroutineExceptionHandler { }) {
            emit(ClassRepository.getClassHomework(it))
        }
    }
    val weekData: LiveData<List<ClassCurriculumItem>> = Transformations.map(type) { type ->
        val calendar = Calendar.getInstance()
        val list = mutableListOf<ClassCurriculumItem>()
        calendar.add(Calendar.DAY_OF_YEAR, type * 7)
        //1 周日 2周一 3周二 4周三
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
        if (dayOfWeek >= 2) {
            calendar.add(Calendar.DAY_OF_YEAR, -(dayOfWeek - 2))
        } else {
            calendar.add(Calendar.DAY_OF_YEAR, -6)
        }
        val now = Calendar.getInstance().timeInMillis.toDateYyyyMMdd()
        for (i in 1..7) {
            val name = /*if (calendar.timeInMillis.toDateYyyyMMdd() == now) "今天" else */"周" + i.chineseNumber.replace("七", "日")
            if (calendar.timeInMillis.toDateYyyyMMdd() == now) {
                list.add(ClassCurriculumItem(name + "今天", calendar.timeInMillis.toDateYyyyMMdd(), ""))
            } else {
                list.add(ClassCurriculumItem(name, calendar.timeInMillis.toDateYyyyMMdd(), ""))
            }
            calendar.add(Calendar.DAY_OF_YEAR, 1)
        }

        list
    }

    fun loadData(weekType: Int = type.value ?: WeekType.CURRENT.type, date: String = selectDate.value!!) {
        val lastWeekType = type.value!!
        if (lastWeekType != weekType) {
            type.value = weekType
            selectDate.value = yyyyMMdd.parse(selectDate.value!!)!!.let {
                Calendar.getInstance().apply {
                    time = it
                    add(Calendar.DAY_OF_YEAR, (weekType - lastWeekType) * 7)
                }
            }.timeInMillis.toDateYyyyMMdd()
            return
        } else if (selectDate.value != date) {
            selectDate.value = date
        }
    }
}
